// Java Document
package DatabaseConnection;

import java.sql.*;

public class DatabaseConnection
{
	
	String connectionString = "jdbc:mysql://127.0.0.1:3306/";
	String defaultDatabase = "test";
	String user = "root";
	String password = "1234567890";
	Connection connection = null;
	Statement statement = null;
	
	public DatabaseConnection()
	{
		try
		{
			Class.forName("org.gjt.mm.mysql.Driver");
		}
		catch (java.lang.ClassNotFoundException e)
		{
			System.err.println(e.getMessage());
		}
	}
	
	public void initDatabase(String hostaddress, String hostport, String hostusername, String hostpassword)
	{
		connectionString = "jdbc:mysql://" + hostaddress + ":" + hostport + "/";
		user = hostusername;
		password = hostpassword;
	}
	
	public ResultSet executeQuery(String sql, String database)
	{
		ResultSet resultset = null;
		try
		{
			connection = DriverManager.getConnection(connectionString + database + "?user=" + user + "&password=" + password);
			statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
			resultset = statement.executeQuery(sql);
		}
		catch (SQLException ex)
		{
			System.err.println("executeQuery:" + ex.getMessage());
			System.err.println("executeQuerySQL:" + sql);
		}
		return resultset;
	}
	
	public ResultSet executeQuery(String sql)
	{
		return executeQuery(sql, defaultDatabase);
	}
	
	public boolean executeUpdate(String sql, String database)
	{
		try
		{
			connection = DriverManager.getConnection(connectionString + database + "?user=" + user + "&password=" + password);
			statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
			statement.executeUpdate(sql);
		}
		catch (SQLException ex)
		{
			System.err.println("executeUpdate:" + ex.getMessage());
			System.err.println("executeUpdateSQL:" + sql);
			return false;
		}
		return true;
	}
	
	public boolean executeUpdate(String sql)
	{
		return executeUpdate(sql, defaultDatabase);
	}
	
	public void closeConnection()
	{
		if (statement != null)
		{
			try
			{
				statement.close();
			}
			catch (SQLException e)
			{
				e.printStackTrace(System.err);
			}
		}
		if (connection != null)
		{
			try
			{
				connection.close();
			}
			catch (SQLException e)
			{
				e.printStackTrace(System.err);
			}
		}
	}
	
}